package cn.techfan.customerserviceconsole;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

@RibbonClient(name="customer-rest-service",configuration = ConsoleRoutingConfig.class)
@Controller
public class DashboardController {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Autowired
    private RestTemplate restTemplate;

    @com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand(fallbackMethod = "getUserBackup")
    @RequestMapping("/dashboard/{id}")
    public String getUser(@PathVariable String id, Model m) {
        User u = restTemplate.getForObject("http://customer-rest-service/user/" + id, User.class);
        m.addAttribute("user",u);
        return "/index";
    }

    public String getUserBackup(@PathVariable String id, Model m) {
        User u = new User("-10000","服务不可达: 请检查customer-rest-service服务是否可用",0);
        m.addAttribute("user",u);
        return "/index";
    }
}
